<?php
/**
 * Class OChosen (OrderedChosen, Ordered Chosen)
 */
class OChosen extends Chosen{
	
	//value attribute yang ada di database
	public $options;
	
	 /** Render widget html and register client scripts */
    public function run()
    {
        list($name, $id) = $this->resolveNameID();
        if (isset($this->htmlOptions['id']))
            $id = $this->htmlOptions['id'];
        else
            $this->htmlOptions['id'] = $id;
        if (isset($this->htmlOptions['name']))
            $name = $this->htmlOptions['name'];

        if ($this->multiple && substr($name, -2) !== '[]')
            $name .= '[]';

        if ($this->multiple && $this->sendEmpty) {
            echo CHtml::hiddenField(substr($name, 0, -2), '', array('id' => false));
        }
        if (isset($this->model)) {
			if(!empty($this->options)){
				//kalau ada options maka set data dari options
				echo CHtml::dropDownList($name, $this->options, $this->data, $this->htmlOptions);
			}else{
				echo CHtml::dropDownList($name, CHtml::resolveValue($this->model, $this->attribute), $this->data, $this->htmlOptions);
			}
        } else {
            echo CHtml::dropDownList($name, $this->value, $this->data, $this->htmlOptions);
        }
        $this->registerScripts($id);
    }
	
	
	private static function buildConfig($config)
    {
		
        if (isset($config['htmlOptions']['options'])) {
            $defaults = $config['htmlOptions']['options'];
            unset($config['htmlOptions']['options']);
            $config = array_merge($defaults, $config);
        }
        return $config;
    }
	
    /** Multiple items select */
    public static function multiSelect($name, $select, $data, $htmlOptions = array())
    {
        return Yii::app()->getController()->widget(__CLASS__, self::buildConfig(array(
            'name' => $name,
            'value' => $select,
            'data' => $data,
            'htmlOptions' => $htmlOptions,
            'multiple' => true,
        )), true);
    }
	
	public static function convertSetting($s){
		$settings = array();
		
		if (isset($s['maxSelectedOptions'])) $settings['max_selected_options'] = $s['maxSelectedOptions'];		
		
		if (isset($s['noResults']))
            $settings['no_results_text'] = $s['noResults'];
        else
            $settings['no_results_text'] = Yii::t('Chosen.main', "No results match");

        //if ($s['disableSearch'] !== false) $settings['disable_search'] = $s['disableSearch'];
        //if ($s['enableSplitWordSearch'] !== true) $settings['enable_split_word_search'] = $s['enableSplitWordSearch'] ;
        //if ($s['groupSearch'] !== true) $settings['group_search'] = $s['groupSearch'] ;
        //if ($s['searchContains'] !== false) $settings['search_contains'] = $s['searchContains'] ;
        //if ($s['singleBackstrokeDelete'] !== true) $settings['single_backstroke_delete'] = $s['singleBackstrokeDelete'] ;
        //if ($s['inheritSelectClasses'] !== false) $settings['inherit_select_classes'] = $s['inheritSelectClasses'] ;
        //if ($s['displaySelectedOptions'] !== true) $settings['display_selected_options'] = $s['displaySelectedOptions'] ;
		return $settings;
	}

    public static function activeMultiSelect($model, $attribute, $data, $htmlOptions = array(),$options= array())
    {
		$hiddenName = CHtml::activeName($model,$attribute.'_multiple');
        $return = CHtml::hiddenField("{$hiddenName}");
		
		$return .= Yii::app()->getController()->widget(__CLASS__, self::buildConfig(array(
            'model' => $model,
            'attribute' => $attribute,
            'data' => $data,
            'htmlOptions' => $htmlOptions,
            'multiple' => true,
			'options'=>$options
        )), true);
		
		$settings = self::convertSetting($htmlOptions['options']);
		$script= self::getSortJs($htmlOptions,$hiddenName,$settings);
		Yii::app()->clientScript->registerScript('ea',$script,CClientScript::POS_READY);
		return $return;
    }
	
	/**
	 * 
	 * @param type $htmlOptions
	 * @param type $hiddenName
	 * @param type $settings
	 * @return type
	 * 
	 * Script untuk menset order pada chosen
	 */
	public function getSortJs($htmlOptions,$hiddenName,$settings){
		$setting = CJavaScript::encode($settings);
		$data = <<<EOT

	$("select.$htmlOptions[class]").each(function(){
    if($(this).data("order")==true){
        //$(this).val('');
        $(this).chosen($setting);
        var \$ordered = $('[name="$hiddenName"]');
        var selected = \$ordered.val().split(',');
        var chosen_object = $(this).data('chosen');
        $.each(selected, function(index, item){
            $.each(chosen_object.results_data, function(i, data){
                if(data.value == item){
                    $("#"+data.dom_id).trigger('mouseup');
                }
            });
        });
        $(this).data("backupVal",$(this).val());
        $(this).change(function(){
            var backup = $(this).data("backupVal");
            var current = $(this).val();
            if(backup == null){
                backup = [];
            }
            if(current == null){
                current = [];
            }
            if(backup.length > current.length){                         
                $.each(backup, function(index, item) { 
                    if($.inArray(item, current) < 0){
                        for(var i=0; i<selected.length; i++){
                            if(selected[i] == item){
                                selected.splice(i,1);
                            }
                        }
                    }
                });
            }else if(backup.length < current.length){
                $.each(current, function(index, item) { 
                    if($.inArray(item, backup) < 0){
                        selected.push(item);
                    }
                });
            }
            \$ordered.val(selected.join(','));
            $(this).data("backupVal",current);
        });
    }else{
        $(this).chosen($setting);
    }
});

EOT;
		return $data;
	}
	
	/** Register client scripts */
    public function registerScripts($id)
    {
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript('jquery');
        if (defined('YII_DEBUG')) {
            $cs->registerScriptFile($this->assetsDir . '/chosen.jquery.js');

            $cs->registerCssFile($this->assetsDir . '/chosen.css');
        } else {
            $cs->registerScriptFile($this->assetsDir . '/chosen.jquery.min.js');
            $cs->registerCssFile($this->assetsDir . '/chosen.min.css');
        }

        $settings = CJavaScript::encode($this->settings);
        //$cs->registerScript("{$id}_chosen", "$('#{$id}').chosen({$settings});");
    }
}